#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#Author: alvayang <alvayang@tabex.org>
#Last Change: 
#Description: 

import sys
from template import indextmpl
from template import badresourcetmpl
from twisted.internet.threads import deferToThread
from twisted.web.client import getPage
import cjson
import traceback
import urllib2
import urllib
import libxml2

urls = '/geturl'


def get_resource(url, req):
    try:
        opener = urllib2.build_opener()
        opener.addHeaders = [
                ('Host',   'mp3.sogou.com'), 
                ('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3'),
                ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
                ('Accept-Language', 'zh-cn,en-us;q=0.7,en;q=0.3'),
                ('Accept-Encoding', 'gzip,deflate'),
                ('Accept-Charset', 'gb18030,utf-8;q=0.7,*;q=0.7'),
                ('Keep-Alive', '115'),
                ('Connection', 'keep-alive'),
                ('Referer', 'http://mp3.sogou.com/')]
        
        ureq = urllib2.Request(url)        
        urllib2.install_opener(opener)
        f = opener.open(ureq)
        buf = ''
        z = f.read(4096)
        while z:
            buf += z
            z =  f.read(4096)
        # 解析XML
        data = buf.decode('gb2312')
        parse_xml(buf, req)
    except:
        print >> sys.stderr, traceback.format_exc()
        stand_error(req)

def stand_error(req):
    ret["status"] = False
    ret["msg"] = "系统错误!"
    req.write(cjson.encode(ret))
    req.close()

def parse_xml(text, req):
    encoding = 'gbk'
    options = libxml2.HTML_PARSE_RECOVER + libxml2.HTML_PARSE_NOWARNING + libxml2.HTML_PARSE_NOERROR
    doc = libxml2.readDoc(text, None, encoding, options).doc
    ctxt = doc.xpathNewContext()
    items = ctxt.xpathEval(u'//downloadList')
    out = []
    ret = {}
    want = [u'size', u'urls', u'urlsource']
    if items:
        for z in items:
            o = {}
            for q in want:
                o[q] = (z.xpathEval(q)[0].get_content()).decode('utf-8') if z.xpathEval(q) else u'没有合理的解释' 
            out.append(o)
        ret["status"] = True
        ret["msg"] = out
    else:
        ret["status"] = False
        ret["msg"] = u'没有搜索到结果'
    req.write(cjson.encode(ret))
    req.close()


class handler:
    def do_POST(self, hreq):
        self.do_GET(hreq)

    def do_GET(self, hreq):
        if hreq.args.has_key('url'):
            key = hreq.args['url'][0]
            deferToThread(get_resource, key, hreq)
        else:
            ret = {}
            ret["status"] = False
            ret["msg"] = "关键字错误!"
            self.write(cjson.encode(ret))
